<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/4
 * Time: 17:22
 */

namespace App\Process;


use App\Utility\BaseEnum;
use App\Utility\RedisTools;
use EasySwoole\Component\Process\AbstractProcess;
use App\Enum\SysEnum;
use App\Utility\DBTools;
use App\Common\SumComm;
use Swoole\Timer;

class UserLogs extends AbstractProcess
{
    private $everyMinute = 2;           //轮循时间间隔三分钟
    private $tableName = 'qc_user_logs';
    public function run($arg)
    {
        BaseEnum::Logger('异步进程执行：初始化 及参数 =>  '.json_encode($arg) ,'user-login');
        $timeStamp = $this->everyMinute * 60 * 1000;
        $this->addTick($timeStamp , function(){
            SumComm::sumALLAgentLineData();                 //#####更新代理线的统计数据######所有代理的运营数据
            UserLogs::writeLoggerToDB($this->tableName);    //#######处理日志的写入DB操作#############
        });
        
        Timer::after(5000, function(){
            SumComm::sumALLAgentLineData();                     //#####第一次就调用######所有代理的运营数据
        });
    }
    
    /**
     * TODO 日志写入DB
     */
    public static function writeLoggerToDB($logTableName = 'qc_user_logs' ){
        $redisobj = new RedisTools();
        $redisobj->select(0);
        $DBObj = DBTools::getPoolDB();
        $DBObj->startTransaction();
        try{
            $logs = $redisobj->hGetAll(SysEnum::USERLOGS_KEY);
            $data = [];
            foreach ($logs as $key => $log) {
                //取出一条删除一条
                $data[$key] = json_decode($log,true);
                $res = $redisobj->hDel(SysEnum::USERLOGS_KEY,$key);
                //BaseEnum::Logger('删除rediskey'.$res,'user-login');
            }
            //批量插入
            $res = $DBObj->insertMulti($logTableName, $data);
            
            if ($res){
                BaseEnum::Logger('执行日志写DB操作成功','user-login');
                $DBObj->commit();
            }else{
                //不成功一条一条添回
                foreach ($data as $key=>$log){
                    $redisobj->hSet(SysEnum::USERLOGS_KEY,$key,json_encode($log,JSON_UNESCAPED_UNICODE));
                }
            }
        }catch(\Throwable $throwable){
            $DBObj -> rollback();
        }finally{
            DBTools::destPoolDB($DBObj);   //释放Pool
        }
        
    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }

}